import time

from absl import app, flags

import pandas as pd

import coin.base.database.util as db_util
from coin.support.accounting.logic.format_util import *
from xunkemgmt.support.accounting.logic.query_request import (_gen_engine, get_all_account_df)
from coin.support.accounting.logic.memcached_querier import \
  MemcachedAccountInfoQuerier

FLAGS = flags.FLAGS


def _convert_to_df(response_list):
  response_list = [response for response in response_list if response]
  account_id = [response.account_id for response in response_list]
  time_to = [
      pretty_time_delta(time.time() - response.query_timestamp) for response in response_list
  ]

  accounting_currency = [
      response.accounting_currency if hasattr(response, 'accounting_currency') else None
      for response in response_list
  ]
  df = pd.DataFrame({
      'account_id': account_id, 'time_to': time_to, 'accounting_currency': accounting_currency
  })
  return df


def query_and_print(account_data, request_list, title, query_func):
  response_list = query_func(request_list)
  data2 = _convert_to_df(response_list)

  data = account_data.merge(data2, how="left", on="account_id")
  data["account_id_time_to"] = data["account_id"].map(str).fillna(
      "") + " | " + data["time_to"].fillna("__:__:__")

  def aggf(x):
    return ",".join(x.tolist())

  datat = pd.pivot_table(data,
                         index=['account_group', 'owner'],
                         columns=['market_type', 'exchange'],
                         values='account_id_time_to',
                         aggfunc=aggf)

  print()
  print(title)
  print(datat.fillna(""))


def query_and_print2(account_data, request_list, title, query_func):
  response_list = query_func(request_list)
  data2 = _convert_to_df(response_list)

  data = account_data.merge(data2, how="left", on="account_id")
  data["account_id_time_to"] = data["account_id"].map(str).fillna(
      "") + " | " + data["time_to"].fillna("__:__:__")
  data["accounting_currency"] = data["accounting_currency"].fillna("___")

  def aggf(x):
    return ",".join(x.tolist())

  datat = pd.pivot_table(data,
                         index=['account_group', 'owner', 'accounting_currency'],
                         columns=['market_type', 'exchange'],
                         values='account_id_time_to',
                         aggfunc=aggf)

  print()
  print(title)
  print(datat.fillna(""))


def account(engine):
  estimate_request_list = get_all_requests()
  nonestimate_request_list = filter_request(estimate_request_list, filter_func=lambda x: (x.market_type, x.exchange, x.owner))
  db_config = db_util.read_db_config(FLAGS.memcached_config)
  querier = MemcachedAccountInfoQuerier(db_config=db_config)

  print("\n\nACCOUNT")
  account_data = get_all_account_df(active=True)

  query_and_print(account_data,
                  nonestimate_request_list,
                  "balance",
                  querier.query_account_balance_history)
  query_and_print(account_data,
                  nonestimate_request_list,
                  "position",
                  querier.query_account_position_history)
  query_and_print2(account_data,
                   estimate_request_list,
                   "balance_estimate",
                   querier.query_balance_estimate_history)
  query_and_print2(account_data,
                   estimate_request_list,
                   "position estimate",
                   querier.query_position_estimate_history)


def main(_):
  pd.set_option('display.width', 1000)
  pd.set_option('display.max_rows', None)
  pd.set_option('display.max_columns', None)

  engine = _gen_engine()
  account(engine)


if __name__ == '__main__':
  flags.DEFINE_string('memcached_config',
                      "../../coin_deploy/support_accounting/db_config/memcached_config_prod.json",
                      'path of database config.')
  app.run(main)
